//
//  COHomeCreateViewController.swift
//  CocoProject
//
//  Created by Ruthless on 2023/8/23.
//

import UIKit
import QMUIKit
import TZImagePickerController

class COHomeCreateViewController: COBaseViewController {
    private var contents: [FoodType] = [.italy, .france, .usa, .russia, .britain, .thailand, .japan, .other]
    private var select: FoodType = .italy
    
    private let type: Int
    private var image: UIImage? {
        didSet {
            if let image = image {
                self.photoImageView.image = image
                self.deleteButton.isHidden = false
            } else {
                self.photoImageView.image = UIImage(named: "编组 13")
                self.deleteButton.isHidden = true
            }
        }
    }
    
    init(type: Int) {
        self.type = type
        super.init(nibName: nil, bundle: nil)
        
        moneyButton.isHidden = type == 0
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        collectionView.reloadData()
    }
    
    override func configUI() {
        view.addSubview(scrollView)
        scrollView.addSubview(mainView)
        mainView.addSubview(photoNameLabel)
        mainView.addSubview(photoImageView)
        mainView.addSubview(deleteButton)
        mainView.addSubview(squareLabel)
        mainView.addSubview(textView)
        mainView.addSubview(collectionView)
        view.addSubview(submitButton)
        view.addSubview(moneyButton)
        
        scrollView.snp.makeConstraints { make in
            make.left.right.equalToSuperview().offset(0)
            make.top.equalToSuperview().offset(statusBarHeight)
            make.bottom.equalTo(submitButton.snp.top).offset(0)
        }
        
        mainView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
            make.width.equalTo(SCREENWIDTH)
        }
        
        photoNameLabel.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(22)
            make.top.equalToSuperview().offset(45)
        }
        
        photoImageView.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(22)
            make.top.equalTo(photoNameLabel.snp.bottom).offset(10)
            make.width.height.equalTo(145)
        }
        
        deleteButton.snp.makeConstraints { make in
            make.right.top.equalTo(photoImageView).inset(10)
        }
        
        squareLabel.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(22)
            make.top.equalTo(photoImageView.snp.bottom).offset(15)
        }
        
        textView.snp.makeConstraints { make in
            make.left.right.equalToSuperview().inset(22)
            make.top.equalTo(squareLabel.snp.bottom).offset(10)
            make.height.equalTo(195)
        }
        
        collectionView.snp.makeConstraints { make in
            make.left.right.equalToSuperview().inset(22)
            make.top.equalTo(textView.snp.bottom).offset(15)
            make.height.equalTo(78)
            make.bottom.equalTo(mainView.snp.bottom).offset(0)
        }
        
        submitButton.snp.makeConstraints { make in
            make.bottom.equalToSuperview().offset(-32-bottomSafeHeight)
            make.left.right.equalToSuperview().inset(22)
            make.height.equalTo(50)
        }
        
        moneyButton.snp.makeConstraints { make in
            make.top.equalTo(submitButton.snp.bottom).offset(10)
            make.centerX.equalToSuperview()
        }
    }

    private lazy var scrollView: UIScrollView = {
        let scrollView = UIScrollView()
        scrollView.backgroundColor = .rgba(17, 7, 41, 1)
        return scrollView
    }()
    
    private lazy var mainView: UIView = {
        let view = UIView()
        view.backgroundColor = .rgba(17, 7, 41, 1)
        return view
    }()
    
    private lazy var photoNameLabel: UILabel = {
        let label = UILabel()
        label.font = .regular(14)
        label.textColor = .white
        label.text = "Photo"
        return label
    }()
    
    private lazy var photoImageView: UIImageView = {
        let imgV = UIImageView(image: UIImage(named: "编组 13"))
        imgV.layer.masksToBounds = true
        imgV.layer.cornerRadius = 10
        
        let tap = UITapGestureRecognizer(target: self, action: #selector(selectImage))
        imgV.addGestureRecognizer(tap)
        imgV.isUserInteractionEnabled = true
        return imgV
    }()
    
    private lazy var deleteButton: UIButton = {
        let btn = UIButton()
        btn.setImage(UIImage(named: "编组 2"), for: .normal)
        btn.isHidden = true
        btn.addTarget(self, action: #selector(clickButton), for: .touchUpInside)
        return btn
    }()
    
    private lazy var squareLabel: UILabel = {
        let label = UILabel()
        label.font = .regular(14)
        label.textColor = .white
        label.text = "Square content"
        return label
    }()
    
    private lazy var textView: UITextView = {
        let tv = UITextView()
        tv.backgroundColor = .rgba(41, 32, 63, 1)
        tv.layer.masksToBounds = true
        tv.layer.cornerRadius = 15
        tv.textColor = .white
        return tv
    }()

    private lazy var collectionView: UICollectionView = {
        let layout = UICollectionViewFlowLayout()
        layout.itemSize = CGSize(width: (SCREENWIDTH-36-40)/4, height: 33)
        layout.minimumLineSpacing = 12
        layout.minimumInteritemSpacing = 10
        let cv = UICollectionView(frame: .zero, collectionViewLayout: layout)
        cv.backgroundColor = .rgba(17, 7, 41, 1)
        cv.delegate = self
        cv.dataSource = self
        cv.register(cellWithClass: COCreateCollectionViewCell.self)
        return cv
    }()
    
    private lazy var submitButton: UIButton = {
        let btn = UIButton()
        let bgLayer1 = CAGradientLayer()
        bgLayer1.colors = [UIColor.rgba(218, 67, 255).cgColor, UIColor.rgba(82, 28, 255).cgColor]
        bgLayer1.locations = [0, 1]
        bgLayer1.frame = CGRect(x: 0, y: 0, width: SCREENWIDTH-38, height: 50)
        bgLayer1.startPoint = CGPoint(x: 1, y: 0.56)
        bgLayer1.endPoint = CGPoint(x: 0.56, y: 0.56)
        btn.layer.insertSublayer(bgLayer1, at: 0)
        
        btn.setTitle("Submit", for: .normal)
        btn.titleLabel?.font = .medium(14)
        btn.setTitleColor(.white, for: .normal)
        
        btn.layer.masksToBounds = true
        btn.layer.cornerRadius = 25
        
        btn.addTarget(self, action: #selector(clickButton), for: .touchUpInside)
        return btn
    }()
    
    private lazy var moneyButton: QMUIButton = {
        let btn = QMUIButton()
        btn.setImage(UIImage(named: "金币"), for: .normal)
        btn.setTitle("30", for: .normal)
        btn.setTitleColor(.white, for: .normal)
        btn.spacingBetweenImageAndTitle = 3
        btn.titleLabel?.font = .regular(12)
        return btn
    }()
}


extension COHomeCreateViewController {
    @objc
    private func clickButton(_ btn: UIButton) {
        if btn == deleteButton {
            self.image = nil
        } else if btn == submitButton {
            self.uploadImage()
        }
    }
    @objc
    private func selectImage() {
        let picker = TZImagePickerController(maxImagesCount: 1, delegate: self)!
        picker.modalPresentationStyle = .fullScreen
        self.present(picker, animated: true)
    }
}


extension COHomeCreateViewController: TZImagePickerControllerDelegate {
    func imagePickerController(_ picker: TZImagePickerController!, didFinishPickingPhotos photos: [UIImage]!, sourceAssets assets: [Any]!, isSelectOriginalPhoto: Bool, infos: [[AnyHashable : Any]]!) {
        self.image = photos.first
    }
}

extension COHomeCreateViewController: UICollectionViewDelegateFlowLayout {
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let type = contents[indexPath.row]

        select = type
//        if select.contains(type) {
//            select.removeAll { item in
//                item == type
//            }
//        } else {
//            select.append(type)
//        }
        
        collectionView.reloadData {
            
        }
    }
}

extension COHomeCreateViewController: UICollectionViewDataSource {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        contents.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withClass: COCreateCollectionViewCell.self, for: indexPath)
        let type = contents[indexPath.row]
        cell.button.setTitle(type.tag, for: .normal)
        cell.addLayer(select == type)
        return cell
    }
}

extension COHomeCreateViewController {
    private func uploadImage() {
        guard let image = image else {
            self.view.makeToast("Please select photo", position: .center)
            return
        }
        
        self.view.makeToastActivity(.center)
        CONetwork.sendRequest(provider: homeProvider, target: .uploadImage(image: image)) { text in
            let photo = text.replacingOccurrences(of: "\"", with: "")
            self.submit(photo)
        } failedBlock: { _, text in
            self.view.hideToastActivity()
            self.view.makeToast(text, position: .center)
        }
    }
    
    private func submit(_ text: String) {
        CONetwork.sendRequest(provider: homeProvider, target: .create(photo: text, content: textView.text ?? "", type: select.rawValue, category: type+1)) { _ in
            self.view.hideToastActivity()
            self.navigationController?.popViewController(animated: true)
        } failedBlock: { _, text in
            self.view.hideToastActivity()
            self.view.makeToast(text, position: .center)
        }

    }
}
